package com.ai_daily.aitiantian.util;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.core.content.FileProvider;

import com.ai_daily.aitiantian.Constants;
import com.ai_daily.aitiantian.base.BaseApp;

import org.greenrobot.eventbus.EventBus;

import java.io.File;

/**
 * 7.0和8.0系统对安装有限制,要分开处理
 */
public class InstallUtil {
    private static String mPath;//下载下来后文件的路径
    public static int UNKNOWN_CODE = 0xf01;
    private static InstallUtil instance;

    public static InstallUtil getInstance() {
        if (instance == null) {
            synchronized (InstallUtil.class) {
                if (instance == null) {
                    instance = new InstallUtil();
                }
            }
        }
        return instance;
    }

    public void install(String path) {
        //mPath 下载下来后文件的路径
        mPath = path;
        // 保存路径
//        new AppCacheManager().setInstallPath(mPath);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startInstallO();
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            startInstallN();
        } else {
            startInstall();
        }
        EventBus.getDefault().post(new MessageEvent(MessageEvent.DOWNLOADSUCCESS_FAIL));
    }

//    public void install() {
//        String path = new AppCacheManager().getInstallPath();
//        if (!TextUtils.isEmpty(path)) {
//            install(path);
//        }
//    }

    /**
     * android1.x-6.x
     */
    private void startInstall() {
        Intent install = new Intent(Intent.ACTION_VIEW);
        install.setDataAndType(Uri.parse("file://" + mPath), "application/vnd.android.package-archive");
        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Activity currentActivity = BaseApp.getInstance().getCurrentActivity();
        if (currentActivity != null) {
            currentActivity.startActivity(install);
        }
    }

    /**
     * android7.x
     */
    private void startInstallN() {
        Activity currentActivity = BaseApp.getInstance().getCurrentActivity();
        if (currentActivity == null) {
            return;
        }
        //参数1 上下文, 参数2 在AndroidManifest中的android:authorities值, 参数3  共享的文件
        Uri apkUri = FileProvider.getUriForFile(currentActivity, Constants.GLOBAL_PROVIDER_PATH, new File(mPath));
        Intent install = new Intent(Intent.ACTION_VIEW);
        //由于没有在Activity环境下启动Activity,设置下面的标签
        install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //添加这一句表示对目标应用临时授权该Uri所代表的文件
        install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        install.setDataAndType(apkUri, "application/vnd.android.package-archive");
        currentActivity.startActivity(install);
    }

    /**
     * android8.x
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    private void startInstallO() {
        final Activity currentActivity = BaseApp.getInstance().getCurrentActivity();
        if (currentActivity == null || currentActivity.isFinishing() || currentActivity.isDestroyed()) {
            return;
        }
        boolean isGranted = currentActivity.getPackageManager().canRequestPackageInstalls();
//        Toast.makeText(currentActivity,"isGranted = "+isGranted,Toast.LENGTH_LONG).show();
        Log.d("TEST","isGranted = "+isGranted);
//        if (isGranted) {
            startInstallN();//安装应用的逻辑(写自己的就可以)
//        } else {
//            new AlertDialog(currentActivity, MsDialogConfigs.getAlertDialogConfig(currentActivity))
//                    .setDialogCancelable(!UpgradeUtil.forceUpdate)
//                    .setMessage(currentActivity.getString(R.string.install_permission))
//                    .setRightButton(currentActivity.getString(R.string.ok_ed), v -> {
//                        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
//                        currentActivity.startActivityForResult(intent, UNKNOWN_CODE);
//                    })
//                    .show();
//        }
    }
}

